(function($) {
    // page /stylebook
    if (document.getElementById('stylebook-app')) {

        var stylebook = angular.module('stylebook', ['ngSanitize', 'ngAnimate']);

        stylebook.filter('kebab', function() {
            return function(input) {
                if (typeof input === 'string') {
                    return _.kebabCase(input);
                } else {
                    console.error('Must be string!');
                }
            }
        });

        stylebook.controller('stylebookController', ['$scope', '$timeout', '$http', function($scope, $timeout, $http) {

            // debug use
            window.$scope = $scope;
            $scope.debug = false;

            // board keys / indexes:
            //
            // looks
            // gender
            // cat (category)
            // color
            // brand
            // season
            // height
            // age
            // hairstyle
            // size
            $scope.data = null;
            $scope.searchBrand = '';

            var url = new URI(location.href);
            // var apiAll = '/sites/all/themes/xenyo_mobile/js/stylebook_dummy.json';
            var apiAll = '/api/v1/mobile/filter-menu' + url.search();

            var $body = $('body');

            $scope.popupInit = function() {
                $scope.board = 'looks';
            }

            $scope.popupOpen = function() {
                $scope.popupInit();
                $scope.popuping = true;
                $body.addClass('no-scroll');
            };

            $scope.popupClose = function() {
                $scope.popuping = false;
                $body.removeClass('no-scroll');
            }

            $scope.goBoard = function(index) {
                // keep current data incase user cancel the selection
                if (index !== 'looks') {
                    $scope.dataOriginal = angular.copy($scope.data[index].selected);
                }

                $scope.board = index;
            }



            $scope.cancel = function() {
                // console.log('cancelled from board: ' + $scope.board);
                // can't just simply copy back from original to selected
                // becoz angular will lost the data binding
                // have to compare the original with all items
                (function searchItem(o, items) {
                    angular.forEach(items, function(v,k) {
                        if (_.has(v, 'items') && Array.isArray(v.items)) {
                            searchItem(o, v.items);
                        }

                        if (o.name === v.name) {
                            $scope.data[$scope.board].selected = $scope.data[$scope.board].items[k];
                        }
                    });
                })($scope.dataOriginal, $scope.data[$scope.board].items);

                $scope.goBoard('looks');
            }

            $scope.done = function() {
                // console.log('done from board: ' + $scope.board);
                $scope.goBoard('looks');
            }

            $scope.accordionToggle = function(e) {
                $(e.currentTarget).toggleClass('active');
            }

            $scope.reset = function() {
                angular.forEach($scope.data, function(v,k) {
                    v.selected = v.items[0];
                });
            }

            $scope.refine = function() {
                angular.forEach($scope.data, function(v,k) {
                    var val = _.has(v.selected, 'tid') ? v.selected.tid : v.selected.value;
                    if (val == 0) {
                        url.removeQuery(k);
                    } else {
                        url.setQuery(k, val);
                    }
                });
                url.normalize();
                window.location.href = url.toString();
            }


            $.get(apiAll).done(function(data) {
                // console.log(data);
                if (Array.isArray(data)) {
                    $scope.data = data[0];
                } else if (typeof data === 'object') {
                    $scope.data = data;
                }

                angular.forEach($scope.data, function(v,k) {
                    // add 'Not selected' item to every section
                    // but only 'Gender' & 'Season' use 'All' instead of 'Not selected'
                    // WTF
                    if (k === 'gender' || k === 'season') {
                        v.items.unshift({
                            name: 'All',
                            value: 0
                        });
                    } else {
                        v.items.unshift({
                            name: 'Not selected',
                            value: 0
                        });
                    }

                    // if selected is 0, it's equal to the new added "not selected" item
                    if (v.selected.value == 0) {
                        v.selected = v.items[0];
                    }

                    // second level (i.e. category)
                    // the 'Not selected' is the parent itself
                    angular.forEach(v.items, function(vv, kk) {
                        if (_.has(vv, 'items')) {
                            vv.items.unshift({
                                name: vv.name,
                                value: vv.value,
                                display: 'Not selected'
                            });
                        }
                    });
                });

                $scope.$apply();
                $timeout(updateBrand);
            });


            // brand is special
            var brandInited = false;
            function updateBrand() {
                $http({
                    method: 'GET',
                    url: '/api/v1/brand?query=' + $scope.searchBrand
                }).then(function (res) {
                    brandInited = true;
                    if (!_.has($scope.data, 'brand')) {
                        $scope.data.brand = {
                            items: [],
                            selected: null
                        }
                    }

                    $scope.data.brand.items = res.data;
                    $scope.data.brand.items.unshift({
                        name: 'Not selected',
                        value: 0
                    });
                    if ($scope.data.brand.selected.value == 0) {
                        $scope.data.brand.selected = $scope.data.brand.items[0];
                    }

                    $scope.brandLoading = false;
                }, function(res) {
                    console.error('Error while getting brand', res);
                    $scope.brandLoading = false;
                });
            }

            $scope.$watch('searchBrand', function(nv, ov) {
                if (brandInited) {
                    (_.debounce(function() {
                        if (nv !== ov) {
                            $scope.brandLoading = true;
                            updateBrand();
                        }
                    }, 300)());
                }
            }, true);

            $scope.popupInit();
            // $timeout(updateBrand);

        }]);
    }


    // authors
    if ($('[ng-app="authors"]').length) {
        var uri = new URI();
        var uid = uri.segment(1);
        var authors = angular.module('authors', ['ngSanitize', 'ngAnimate']);

        authors.filter('date1', function() {
            return function(item) {
                return moment(item, 'YYYYMM').format('MMMM YYYY');
            };
        });

        authors.filter('to_trusted', ['$sce', function($sce){
            return function(text) {
                return $sce.trustAsHtml(text);
            };
        }]);

        authors.filter('to_url', function() {
            return function(item) {
                var el = $(item);
                if (el.is('[href]')) {
                    return el.attr('href');
                } else if (el.is('[src]')) {
                    return el.attr('src');
                }
                return item;
            };
        });

        authors.filter('to_text', function() {
            return function(item) {
                var el = $(item);
                return el.text();
            }
        });

        authors.factory('authorsFactory', ['$q', '$timeout', '$http', '$rootScope',
            function($q, $timeout, $http, $rootScope) {

            var apiBase = '/jessica/api/';
            var api = {
                content: apiBase + 'restapi_views/author_content?display_id=embed_1&args[]=' + uid + '&args[]=all',
                profile: apiBase + 'restapi_views/author_profile?display_id=default&args[]=' + uid,
                archives: apiBase + 'restapi_views/author_content?display_id=block_1&args[]=' + uid,
                popular: apiBase + 'restapi_views/most_read?display_id=block'
            };
            $rootScope.contentPage = 0;

            function getData(type) {
                var defer = $q.defer();

                var url = api[type];
                if (type === 'content') {
                    url += '&page=' + $rootScope.contentPage;
                }
                $http({
                    method: 'GET',
                    url: url
                }).then(function(res) {
                    defer.resolve(res);
                }, function(err) {
                    console.error(err);
                    defer.reject();
                });

                return defer.promise;
            }

            return {
                getData: getData
            };
        }]);

        authors.controller('authorsCtrl', ['$scope', 'authorsFactory', '$timeout', '$rootScope',
            function($scope, authorsFactory, $timeout, $rootScope) {
                window.$scope = $scope;

                authorsFactory.getData('profile')
                    .then(function(res) {
                        $scope.profile = res.data.content[0];
                        // console.log($scope.profile);
                        return authorsFactory.getData('content');
                    })
                    .then(function(res) {
                        $scope.content = res.data.content;
                        $rootScope.contentPage++;
                        // console.log($scope.content);
                        return authorsFactory.getData('archives');
                    })
                    .then(function(res) {
                        $scope.archives = res.data.content;
                        // console.log($scope.archives);
                        return authorsFactory.getData('popular');
                    })
                    .then(function(res) {
                        $scope.popular = res.data.content;
                        // console.log($scope.popular);
                    });

            $scope.loadmore = function() {
                authorsFactory.getData('content').then(function(res) {
                    $scope.content = $scope.content.concat(res.data.content);
                    $rootScope.contentPage++;
                });
            }

        }]);
    }


    // page msw
    if ($('[ng-app="msw"]').length) {
        var msw = angular.module('msw', ['ngSanitize', 'ngAnimate', 'checklist-model']);
        msw.filter('to_url', function() {
            return function(item) {
                var el = $(item);
                if (el.is('[href]')) {
                    return el.attr('href');
                } else if (el.is('[src]')) {
                    return el.attr('src');
                }
                return item;
            };
        });
        msw.filter('to_text', function() {
            return function(item) {
                var el = $(item);
                return el.text();
            }
        });
        msw.factory('mswFactory', ['$q', '$http', '$timeout',
            function($q, $http, $timeout) {
                var apiBase = '/jessica/api/';
                var api = {
                    search: apiBase + 'restapi_views/msw_home',
                    industry: apiBase + 'restapi_views/msw_industry',
                    mostview: apiBase + 'restapi_views/msw_home?display_id=block_1'
                };

                function getIndustry() {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.industry
                    }).then(function(res) {
                        defer.resolve(res.data.content);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                function getMostview() {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.mostview
                    }).then(function(res) {
                        defer.resolve(res.data.content);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                function search(params) {
                    var defer = $q.defer();
                    $http({
                        method: 'GET',
                        url: api.search + params
                    }).then(function(res) {
                        defer.resolve(res.data.content);
                    }, function(err) {
                        console.error(err);
                        defer.reject();
                    });
                    return defer.promise;
                }

                return {
                    getIndustry: getIndustry,
                    getMostview: getMostview,
                    search: search
                }
            }
        ]);

        msw.controller('mswCtrl', ['$scope', 'mswFactory', '$timeout',
            function($scope, mswFactory, $timeout) {
                window.$scope = $scope;


                $scope.hasFilter = false;
                $scope.loading = true;
                mswFactory.getMostview().then(function(res) {
                    $scope.mostview = res;
                    $scope.loading = false;
                });

                $scope.alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
                mswFactory.getIndustry().then(function(content) {
                    $scope.industry = content;
                });
                $scope.selected = {
                    alphabet: [],
                    industry: []
                };
                $scope.searchText = '';

                $scope.reset = function() {
                    $scope.selected = {
                        alphabet: [],
                        industry: []
                    };
                    $scope.searchText = '';
                    $scope.hasFilter = false;
                    $scope.loading = false;
                }

                $scope.onKeyup = function(e) {
                    if (e.keyCode === 13) {
                        $scope.search();
                    }
                }

                $scope.search = function() {
                    if ($scope.selected.alphabet.length === 0
                        && $scope.selected.industry.length === 0
                        && $scope.searchText.length === 0) {
                        $scope.hasFilter = false;
                        return;
                    }

                    $scope.hasFilter = true;
                    $scope.loading = true;

                    if ($scope.selected.alphabet.length) {
                        uri.setSearch('alphabetic_search[]', $scope.selected.alphabet);
                    } else {
                        uri.removeSearch('alphabetic_search[]');
                    }

                    if ($scope.selected.industry.length) {
                        uri.setSearch('field_industry_tid[]', $scope.selected.industry);
                    } else {
                        uri.removeSearch('field_industry_tid[]');
                    }

                    if ($scope.searchText.length) {
                        uri.setSearch('field_msw_english_name_value', $scope.searchText);
                    } else {
                        uri.removeSearch('field_msw_english_name_value');
                    }

                    mswFactory.search(uri.readable()).then(function(res) {
                        $scope.searchResult = res;
                        $scope.loading = false;
                    });
                }

                var uri = new URI('?display_id=page');
                $scope.$watch('selected', function(nv,ov) {
                    if (nv !== ov) {
                        $scope.search();
                    }
                }, true);

            }
        ]);
    }



})(jQuery);
